<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>聊天室</title>
</head>
<body>

<div style="width: 600px;height: 400px;">
    <p>服务器输出:</p>
    <div style="border: 1px solid #CCC;height: 300px;overflow: scroll" id="server-msg-container">
    </div>
    <p>
        <textarea id="msg" style="height: 50px;width: 500px"></textarea><input type="button" value="发送" id="send">
    </p>
</div>

<script type="application/javascript">

    var heartbeatHandler = null;

    var ws = new WebSocket("ws://127.0.0.1:2688/websocket");
    ws.onopen = function (ev) {
        heartbeatHandler = setInterval(function () {
            heartbeat(ws)
        }, 3000);
    };
    ws.onmessage = function (ev) {
        console.info("onmessage", ev);
        var inpMsg = document.getElementById("server-msg-container");
        if (typeof ev.data === "string") {
            inpMsg.innerHTML += ev.data + "<br/>";
        } else {
            var result = ev.data;
            console.log("返回的是二进制数据！");
        }
    };
    ws.onerror = function () {
        var inpMsg = document.getElementById("server-msg-container");
        inpMsg.innerHTML += "发生异常" + "<br/>";
    };
    ws.onclose = function () {
        var inpMsg = document.getElementById("server-msg-container");
        inpMsg.innerHTML += "webSocket 关闭" + "<br/>";
        //清除心跳定时
        if (heartbeatHandler != null) clearInterval(heartbeatHandler);
    };

    // 发送文字消息
    document.getElementById("send").addEventListener("click", function () {
        ws.send(JSON.stringify({
            "head": {"id": 8888},
            "body": document.getElementById("msg").value
        }));
    }, false);

    // 心跳
    function heartbeat(ws) {
        ws.send(JSON.stringify({
            "head": {"id": 1}
        }));
    }

</script>

</body>
</html>